package com.wardrobe.configuration;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages={"com.wardrobe.mapper.master"},sqlSessionFactoryRef="masterSqlSessionFactory")
public class MasterMapperScanConfiguration {
	
	@Resource
	private DataSource masterDataSource;
	
	@Bean
	public SqlSessionFactory masterSqlSessionFactory() throws Exception{
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(masterDataSource);
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		bean.setConfigLocation(resolver.getResource("classpath:mybatis-config.xml"));
		bean.setMapperLocations(resolver.getResources("classpath:com/wardrobe/mapperfile/master/**/*.xml"));
		return bean.getObject();
	}
	
	
	@Bean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(masterDataSource);
    }
	
	
	@Bean
    public SqlSessionTemplate sqlSessionTemplate1() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(masterSqlSessionFactory()); // 使用上面配置的Factory
        return template;
    }

}
